<?php

use com\gdl\newagk\interfaces\ActionServiceIf;
use com\gdl\newagk\dataobject\action\LoginRequestDTO;
use com\gdl\newagk\dataobject\action\LoginResultDTO;
use com\gdl\newagk\dataobject\action\RegisterRequestDTO;
use com\gdl\newagk\dataobject\action\RegisterResultDTO;
use com\gdl\newagk\dataobject\action\ApproveRequestDTO;
use com\gdl\newagk\dataobject\action\ApproveResultDTO;
use com\gdl\newagk\dataobject\action\UserInfoResultDTO;
use com\gdl\common\dataobject\common\ResultDO;
/**
 *  uc 用户登录
 *  @author gdl
 */
class api_ActionService extends api_Abstract implements ActionServiceIf
{
	static public $photo = "http://ot7pftuwd.bkt.clouddn.com/jgg8s6pc_264rfqm9vgty5ae187f645c25.jpg";
    public function login(LoginRequestDTO $loginDO)
    {
        $condition = array();
        $data = array();
        try {
            $resultDO = new LoginResultDTO();
            $resultDO->data = [];
			$resultDO->success = TRUE;
            $username = gdl_lib_BaseUtils::getStr($loginDO->username, 'string');
            $pwd = gdl_lib_BaseUtils::getStr($loginDO->password, 'string');
            $type = gdl_lib_BaseUtils::getStr($loginDO->type, 'string');
            $way = gdl_lib_BaseUtils::getStr($loginDO->way,'int');
            $condition[$type] = $username;
            $condition['way'] = $way;

            $modelMember = new model_agkuc_ucentermember();
            $model = new model_agkuc_member();
            $user = $modelMember->selectOne($condition);
		 
            if ($user['id']) {
                /* 老平台转密码验证 */
                if ($user['passsalt'] == 'aa123456') {
                    $password = $pwd === '' ? '' : md5(sha1($pwd) . '*]f)={.zRuS;FZWUv6"TGJPO_5g<Kx#~k&|7nj(I');
                } else {
                    $password = md5((gdl_lib_BaseUtils::IsMd5($pwd) ? md5($pwd) : md5(md5($pwd))) . $user['passsalt']);
                }

                if ($password == $user['password']) {
					
                    $update = ['last_login_ip' => gdl_lib_BaseUtils::getIp('000.000.000.00'),'last_login_time' => $this->_time];
                    $modelMember->updateUcenterData($user['id'], $update);
                    $model->updateUcenterData($user['id'], $update);
                  
					# 查user
					$userModel = new model_newagk_user();
					$userid = $userModel->selectOne("gdlUserid='{$user['id']}' and isdelete=0","userId,photo,isdelete,status");
					  
					#已被删除
					if(empty($userid)){
						$resultDO->message = "用户已被删除";
						return $resultDO;
					}
					
					#已被禁用
					if($userid['status']!=1 && isset($userid['status']) && $userid['isdelete']==0){
						$resultDO->message = "用户已被禁用，请联系平台管理员开启";
						return $resultDO;
					}
					
                    # 再查newagk 里的user_companyid
                    $userCompany = new model_newagk_usercompany();
                    $userCompanyData = $userCompany->selectOne("userId='{$userid['userId']}' and defaultPlaform=1 and status=1 and isdelete=0","id,userId,platformId,companyId");
					# 统计有几个平台
					$p_leftJoin = array('agk_user_company as uc' => 'agk_platform.id=uc.platformId');
					$p_condition['uc.userId'] = $userid['userId'];
					$p_condition['agk_platform.status'] = 1;
					$p_condition['uc.isdelete'] = 0;
					$p_items = 'agk_platform.id,agk_platform.parentid,agk_platform.`reals`,uc.id as indetity_id,agk_platform.reals,agk_platform.adminRealname';
					$p_groupBy = 'group by agk_platform.id';
					$modelPlaform = new model_newagk_platform();
					$platformRes = $modelPlaform->select($p_condition, $p_items, $p_groupBy, '', $p_leftJoin)->items; 
					$platformCount = !empty($platformRes) ? count($platformRes) : 0;
					
					$identity_id = $userCompanyData['id']?$userCompanyData['id'] : 0;
                    $platform_id = $userCompanyData['platformId']?$userCompanyData['platformId'] : 0;
                    $company_id = $userCompanyData['companyId']?$userCompanyData['companyId'] : 0;
					$userLogo = $userid['photo'] ? $userid['photo'] : self::$photo;
					
					$platformName = "";
					foreach($platformRes as $key){
						
						if($key['id']==$platform_id && $platform_id!=0){
							
							$platformName = $key['reals'];
						}
					}
					
                    $resultDO->data = ['username' => $user['username'],'truename'=>$user['truename'],'userid'=>$userid['userId'],'gdl_userid'=> $user['id'],'idcard' => $user['idcard'],
                                        'identity_id'=>$identity_id,'platform_id'=>$platform_id,'company_id'=>$company_id,'photo'=>$userLogo,'phone'=>$user['mobile'],'platformCount'=>$platformCount,'platformName'=>$platformName];
                    $resultDO->success = TRUE;
                    $resultDO->code = 200;
                    $resultDO->message = '登录成功';
                    $resultDO->uid = $user['id'];
                } else {
                    $resultDO->success = TRUE;
                    $resultDO->code = 400;
                    $resultDO->message = '密码不正确';
                    $resultDO->uid = 400;
                }
            } else {
                $resultDO->success = TRUE;
                $resultDO->code = 400;
                $resultDO->message = '用户名不存在';
                $resultDO->uid = 400;
            }
        } catch (Exception $ex) {
            $resultDO->success = FALSE;
            $resultDO->message = $ex->getMessage();
            $resultDO->code = $ex->getCode();
        }
        return $resultDO;
    }

    public function passwordVerify(UserInfoResultDTO $UserDO){
        $condition = array();
        $data = array();
        try {
            $resultDO = new LoginResultDTO();
            $name = gdl_lib_BaseUtils::getStr($UserDO->name, 'string');
            $type = gdl_lib_BaseUtils::getStr($UserDO->type, 'string');
            $pwd = gdl_lib_BaseUtils::getStr($UserDO->field, 'string');//此处传递密码
            $condition[$type] = $name;
            $modelMember = new model_agkuc_ucentermember();
            $user = $modelMember->selectOne($condition);

            if ($user['username']) {
                    if ($user['passsalt'] == 'aa123456') {
                        $password = $pwd === '' ? '' : md5(sha1($pwd) . '*]f)={.zRuS;FZWUv6"TGJPO_5g<Kx#~k&|7nj(I');
                    } else {
                        $password = md5((gdl_lib_BaseUtils::IsMd5($pwd) ? md5($pwd) : md5(md5($pwd))) . $user['passsalt']);
                    }
                    if ($password == $user['password']) {
                        $resultDO->success = TRUE;
                        $resultDO->code = 1;
                        $resultDO->message = '密码正确';
                        $resultDO->uid = $user['id'];
                    } else {
                        $resultDO->success = TRUE;
                        $resultDO->code = 0;
                        $resultDO->message = '用户名或密码不正确';
                        $resultDO->uid = 0;
                    }

            } else {
                $resultDO->success = TRUE;
                $resultDO->code = 0;
                $resultDO->message = '用户不存在';
                $resultDO->uid = 0;
            }
        } catch (Exception $ex) {
            $resultDO->success = FALSE;
            $resultDO->message = $ex->getMessage();
            $resultDO->code = $ex->getCode();
        }
        return $resultDO;
    }

    public function editUcPassword(LoginRequestDTO $loginDO){
        try {
            $resultDO = new LoginResultDTO();
            $username = gdl_lib_BaseUtils::getStr($loginDO->username, 'string');
            $pwd = gdl_lib_BaseUtils::getStr($loginDO->password, 'string');
            $type = gdl_lib_BaseUtils::getStr($loginDO->type, 'string');
            $modelMember = new model_agkuc_ucentermember();
            $condition[$type] = $username;
            $list = $modelMember->selectOne($condition,'id,passsalt');
            if (!empty($list)) {
                $password_new = md5((md5(md5($pwd))) . $list['passsalt']);
                $rs = $modelMember->update(['id' => $list['id']],['password' => $password_new]);
            } else {
                $resultDO->success = TRUE;
                $resultDO->code = 0;
                $resultDO->message = '用户不存在';
                $resultDO->uid = $list['id'];
            }
            if ($rs) {
                $resultDO->success = TRUE;
                $resultDO->code = 1;
                $resultDO->message = '修改成功';
                $resultDO->uid = $list['id'];
            } else {
                $resultDO->success = TRUE;
                $resultDO->code = 0;
                $resultDO->message = '新密码与旧密码相同';
                $resultDO->uid = $list['id'];
            }
        }catch (Exception $ex) {
                $resultDO->success = FALSE;
                $resultDO->message = $ex->getMessage();
                $resultDO->code = $ex->getCode();
        }
        return $resultDO;
    }

    public function registerUser(RegisterRequestDTO $RegisterDO) 
    {   
        try {
            $resultDO = new RegisterResultDTO();
            $username = $RegisterDO->username ? gdl_lib_BaseUtils::getStr($RegisterDO->username, 'string') : '';
            $password = $RegisterDO->password ? gdl_lib_BaseUtils::getStr($RegisterDO->password, 'string') : '';
            $truename = $RegisterDO->truename ? gdl_lib_BaseUtils::getStr($RegisterDO->truename, 'string') : '';
            $mobile = $RegisterDO->mobile ? gdl_lib_BaseUtils::getStr($RegisterDO->mobile, 'string') : '';
            $idcard = $RegisterDO->idcard ? gdl_lib_BaseUtils::getStr($RegisterDO->idcard, 'string') : '';
            $email = $RegisterDO->email ? gdl_lib_BaseUtils::getStr($RegisterDO->email, 'string') : '';
            $way = $RegisterDO->way ? gdl_lib_BaseUtils::getStr($RegisterDO->way, 'string') : '';
            $account_type = $RegisterDO->account_type ? gdl_lib_BaseUtils::getStr($RegisterDO->account_type,'string') : 1;
            $modelUcenterMember = new model_agkuc_ucentermember();

            //检查是否存在相同用户
            if ($idcard) {
                $existWhere = ['idcard' => $idcard];
                $existRes = $modelUcenterMember->selectOne($existWhere, 'id');
                if ($existRes['id']) {
                    $resultDO->success = TRUE;
                    $resultDO->code = 0;
                    $resultDO->message = '注册失败，身份证已存在';
                    return $resultDO;
                }
                
            }

            if ($mobile) {
                $existWhere = ['mobile' => $mobile];
                $existRes = $modelUcenterMember->selectOne($existWhere, 'id');
                if ($existRes['id']) {
                    $resultDO->success = TRUE;
                    $resultDO->code = 0;
                    $resultDO->message = '注册失败，手机号码已存在';
                    return $resultDO;
                }
                
            }

            //注册
            $insert = [];
            $insert['username'] = $username;
            $insert['truename'] = $truename;
            $insert['passsalt'] = parent::random(8);
            $insert['password'] = parent::dpassword($password, $insert['passsalt']);
            $insert['email'] = $email;
            $insert['mobile'] = $mobile;
            $insert['idcard'] = $idcard;
            $insert['reg_time'] = $this->_time;
            $insert['status'] = 1;
            $insert['type'] = 1;
            $insert['way'] = $way;
            $insert['account_type'] = $account_type;
            $ret = $modelUcenterMember->insert($insert);
            if ($ret) {
                $modelMember = new model_agkuc_member();
                $inserMember = [
                    'nickname' => $username,
                    'reg_time' => $this->_time, 'status' => 1,
                    'last_login_role' => 1,
                    'show_role' => 1,
                ];
                $retMember = $modelMember->insert($inserMember);
                if ($retMember) {
                    $resultDO->success = TRUE;
                    $resultDO->code = 1;
                    $resultDO->message = '注册成功';
                    $resultDO->uid = $ret;
                } else {
                    $resultDO->success = TRUE;
                    $resultDO->code = 0;
                    $resultDO->message = $modelMember->getError();
                }
            } else {
                $resultDO->success = TRUE;
                $resultDO->code = 0;
                $resultDO->message = $modelUcenterMember->getError();
            }
        } catch (Exception $ex) {
            $resultDO->success = FALSE;
            $resultDO->code = 0;
            $resultDO->message = $ex->getMessage();
        }
        return $resultDO;
    }

    public function editUcUser($userid,RegisterRequestDTO $EditDO) 
    {
        try {
            $resultDO = new ResultDO();
            $password = $EditDO->password ? gdl_lib_BaseUtils::getStr($EditDO->password, 'string') : '';
            $args['truename'] = $EditDO->truename ? gdl_lib_BaseUtils::getStr($EditDO->truename, 'string') : '';
            $args['mobile'] = $EditDO->mobile ? gdl_lib_BaseUtils::getStr($EditDO->mobile, 'string') : '';
            $args['idcard'] = $EditDO->idcard ? gdl_lib_BaseUtils::getStr($EditDO->idcard, 'string') : '';
            $args['email'] = $EditDO->email ? gdl_lib_BaseUtils::getStr($EditDO->email, 'string') : '';
            $serviceMember = new service_member();
            $modelMember = new model_agkuc_ucentermember();

            if($args['email']){
                if (!gdl_lib_BaseUtils::IsEmail($args['email'])) unset($args['email']);
            }
            if($args['idcard']){
                if (!gdl_lib_BaseUtils::idcard_verify_number($args['idcard'])) unset($args['idcard']);
            }
            if($args['mobile']){
                if (!gdl_lib_BaseUtils::IsMobile($args['mobile'])) unset($args['mobile']);
            }
            
            if ($userid) {
                //修改
                $condition = ['id' => $userid];
                $usermobile = $modelMember->selectOne($condition, 'id,passsalt');
                if (!empty($usermobile['id'])) {
                    if ($password) {
                        $args['password'] = $serviceMember->dpassword($password, $usermobile['passsalt']);
                    }

                    $modelMember->update(['id' => $userid], $args);
                    $resultDO->success = TRUE;
                    $resultDO->code = 1;
                    $resultDO->message = '修改成功';
                } else {
                    $resultDO->success = TRUE;
                    $resultDO->code = 0;
                    $resultDO->message = '修改失败,信息不存在';
                }
            }
        } catch (Exception $ex) {
            $resultDO->success = FALSE;
            $resultDO->code = 0;
            $resultDO->message = $ex->getMessage();
        }
        return $resultDO;
    }
    
    public function approve(ApproveRequestDTO $ApproveDO) 
    {
        try {
            $resultDO = new ApproveResultDTO();
            $ucid = $ApproveDO->ucid ? gdl_lib_BaseUtils::getStr($ApproveDO->ucid ,'int') : 0;
            $data = $ApproveDO->data;
            $type = $ApproveDO->type ? gdl_lib_BaseUtils::getStr($ApproveDO->type, 'int') : 0;

            if (!$type) {
                $resultDO->success = true;
                $resultDO->code = 0;
                $resultDO->message = '缺少用户类型';
                $resultDO->ucid = 0;
            }

            $ucenterMemberCondition = [
                'id' => $ucid
            ];
            $memberCondition = [
                'uid' => $ucid
            ];

            if ($type == 1) {
                //用户基础数据
                $data->truename ? $ucenterMemberData['truename'] = gdl_lib_BaseUtils::getStr($data->truename) : '';
                $data->idcard ? $ucenterMemberData['idcard'] = gdl_lib_BaseUtils::getStr($data->idcard) : '';
                //用户扩展数据
                $data->idcard_front ? $memberData['idcard_front'] = gdl_lib_BaseUtils::getStr($data->idcard_front) : '';
                $data->idcard_back ? $memberData['idcard_back'] = gdl_lib_BaseUtils::getStr($data->idcard_back) : '';
                $data->sex ? $memberData['sex'] = gdl_lib_BaseUtils::getStr($data->sex) : '';
                $data->avatar ? $memberData['avatar'] = gdl_lib_BaseUtils::getStr($data->avatar) : '';
            } elseif ($type == 2) {
                //用户基础数据  
                $data->company_name ? $memberData['company_name'] = gdl_lib_BaseUtils::getStr($data->company_name) : '';
                $data->company_code ? $memberData['company_code'] = gdl_lib_BaseUtils::getStr($data->company_code) : '';
                //用户扩展数据
                $data->sex ? $memberData['sex'] = gdl_lib_BaseUtils::getStr($data->sex) : '';
                $data->company_page ? $memberData['company_page'] = gdl_lib_BaseUtils::getStr($data->company_page) : '';
                $data->avatar ? $memberData['avatar'] = gdl_lib_BaseUtils::getStr($data->avatar) : '';
            }


            $ucenterMemberModel = new model_agkuc_ucentermember();
            $memberModel = new model_agkuc_member();

            $ucenterMemberModel->beginTransaction();
            $u = $ucenterMemberModel->update($ucenterMemberCondition, $ucenterMemberData);
            $m = $memberModel->update($memberCondition, $memberData);
            if ($u && $m) {
                $ucenterMemberModel->commit();
            } else {
                $ucenterMemberModel->rollBack();
            }

            $resultDO->success = true;
            $resultDO->code = 1;
            $resultDO->message = '认证成功';
            $resultDO->ucid = $ucid;
        } catch (Exception $ex) {
            $resultDO->success = FALSE;
            $resultDO->code = 0;
            $resultDO->message = $ex->getMessage();
        }
        return $resultDO;
    }

}
